import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as path;

import '../AI/tina_dart/BaseAPI.dart';
import '../AI/dify_datasets.dart';
import '../models/user_info.dart';
import '../main.dart';
import '../serve/file_serve.dart';

class WelcomePage extends StatefulWidget {
  final BaseAPI llm;
  final DifyKnowledgeDatabase difyKnowledge;
  final String appDataDir;
  final FileServe fileServe;

  const WelcomePage({
    Key? key,
    required this.llm,
    required this.difyKnowledge,
    required this.appDataDir,
    required this.fileServe,
  }) : super(key: key);

  @override
  _WelcomePageState createState() => _WelcomePageState();
}

class _WelcomePageState extends State<WelcomePage> with SingleTickerProviderStateMixin {
  final TextEditingController _nicknameController = TextEditingController();
  final TextEditingController _customTagController = TextEditingController();
  final List<String> _selectedTags = [];
  final List<String> _availableTags = [
    '学生',
    '老师',
    '人工智能爱好者',
    '程序员',
    '设计师',
  ];
  bool _isLoading = false;
  String _loadingMessage = '初始化中...请稍候';
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 1000),
    );
    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Interval(0.0, 0.6, curve: Curves.easeOut)),
    );
    _slideAnimation = Tween<Offset>(begin: Offset(0, 0.2), end: Offset.zero).animate(
      CurvedAnimation(parent: _animationController, curve: Interval(0.2, 1.0, curve: Curves.easeOut)),
    );
    _animationController.forward();
  }

  @override
  void dispose() {
    _nicknameController.dispose();
    _customTagController.dispose();
    _animationController.dispose();
    super.dispose();
  }

  void _addCustomTag() {
    final customTag = _customTagController.text.trim();
    if (customTag.isNotEmpty) {
      setState(() {
        if (!_availableTags.contains(customTag)) {
          _availableTags.add(customTag);
          _selectedTags.add(customTag);
        } else if (!_selectedTags.contains(customTag)) {
          _selectedTags.add(customTag);
        }
        _customTagController.clear();
      });
    }
  }

  Future<void> _saveUserInfoAndinitDifydataset() async {
    if (_nicknameController.text.isEmpty) {
      _showErrorMessage('请输入昵称');
      return;
    }

    if (_selectedTags.isEmpty) {
      _showErrorMessage('请至少选择一个身份标签');
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      String nickname = _nicknameController.text;
      final userInfo = UserInfo(
        nickname: nickname,
        identityTags: _selectedTags,
      );

      await widget.fileServe.saveUserInfo(userInfo.toJson());
      
      setState(() {
        _loadingMessage = '正在初始化知识库...';
      });
      
      String datasetName = '${nickname}的知识库';
      String datasetDescription = '${nickname}的个人知识管理系统';
      String aboutMdPath = path.join(widget.appDataDir, 'doc', 'about.md');
      
      try {
        final datasetResult = await widget.difyKnowledge.createDataset(
          datasetName,
          datasetDescription,
          aboutMdPath
        );
        
        if (datasetResult != null) {
          final configPath = path.join(widget.fileServe.returnConfigPath(), 'dify_dataset.json');
          Map<String, dynamic> difyConfig = await widget.fileServe.getConfig('Dify');
          difyConfig['dataset_name'] = datasetName;
          await widget.fileServe.changeDifyDatasetConfig(difyConfig);
        }
      } catch (e) {
        print('创建知识库时出错: $e');
      }

      Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (context) => MainNavigationPage(),
        ),
      );
    } catch (e) {
      _showErrorMessage('保存用户信息失败: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _showErrorMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red[400],
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        margin: EdgeInsets.all(16),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      body: _isLoading
          ? _buildLoadingScreen()
          : _buildWelcomeScreen(),
    );
  }

  // 美化的加载界面
  Widget _buildLoadingScreen() {
    return Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF667eea),
            Color(0xFF764ba2),
          ],
                ),
              ),
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
            // 美化的logo容器
            Container(
              width: 120,
              height: 120,
              decoration: BoxDecoration(
                color: Colors.white,
                shape: BoxShape.circle,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 30,
                    offset: Offset(0, 15),
                  ),
                ],
              ),
              child: Padding(
                padding: EdgeInsets.all(20),
                child: ClipOval(
                  child: Image.asset(
                    'assets/images/logo.png',
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),
            SizedBox(height: 40),
            
            // 加载指示器
            Container(
              width: 60,
              height: 60,
              child: CircularProgressIndicator(
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                strokeWidth: 3,
              ),
                    ),
            SizedBox(height: 32),
            
            // 加载文本
            Container(
              padding: EdgeInsets.symmetric(horizontal: 32, vertical: 16),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.1),
                borderRadius: BorderRadius.circular(20),
                border: Border.all(color: Colors.white.withOpacity(0.2)),
              ),
              child: Text(
                      _loadingMessage,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                  fontWeight: FontWeight.w600,
                  letterSpacing: 0.5,
                ),
                      ),
                    ),
                  ],
                ),
              ),
    );
  }

  // 美化的欢迎界面
  Widget _buildWelcomeScreen() {
    return Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF667eea),
            Color(0xFF764ba2),
          ],
                ),
              ),
              child: SafeArea(
                child: SingleChildScrollView(
          child: Column(
            children: [
              // 顶部装饰区域
              Container(
                padding: EdgeInsets.fromLTRB(32, 40, 32, 60),
                    child: FadeTransition(
                      opacity: _fadeAnimation,
                      child: SlideTransition(
                        position: _slideAnimation,
                        child: Column(
                          children: [
                        // 美化的logo
                        Container(
                          width: 140,
                          height: 140,
                                decoration: BoxDecoration(
                            color: Colors.white,
                                  shape: BoxShape.circle,
                                  boxShadow: [
                                    BoxShadow(
                                color: Colors.black.withOpacity(0.15),
                                blurRadius: 30,
                                offset: Offset(0, 15),
                              ),
                              BoxShadow(
                                color: Colors.white.withOpacity(0.3),
                                      blurRadius: 20,
                                offset: Offset(0, -5),
                                    ),
                                  ],
                                ),
                          child: Padding(
                            padding: EdgeInsets.all(24),
                                child: ClipOval(
                                  child: Image.asset(
                                    'assets/images/logo.png',
                                    fit: BoxFit.cover,
                                  ),
                                ),
                              ),
                            ),
                        SizedBox(height: 32),
                        
                        // 欢迎文本
                        Column(
                          children: [
                            Text(
                              '欢迎使用知拾',
                              style: TextStyle(
                                fontSize: 36,
                                fontWeight: FontWeight.w800,
                                color: Colors.white,
                                letterSpacing: 1,
                              ),
                            ),
                            SizedBox(height: 12),
                            Container(
                              padding: EdgeInsets.symmetric(horizontal: 24, vertical: 8),
                              decoration: BoxDecoration(
                                color: Colors.white.withOpacity(0.15),
                                borderRadius: BorderRadius.circular(20),
                                border: Border.all(color: Colors.white.withOpacity(0.2)),
                              ),
                              child: Text(
                              '你的个人知识管理系统',
                              style: TextStyle(
                                fontSize: 16,
                                  fontWeight: FontWeight.w500,
                                  color: Colors.white.withOpacity(0.9),
                                  letterSpacing: 0.5,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              
              // 表单区域
              Container(
                margin: EdgeInsets.symmetric(horizontal: 24),
                padding: EdgeInsets.all(32),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(32),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 30,
                      offset: Offset(0, 20),
                    ),
                  ],
                ),
                child: FadeTransition(
                  opacity: _fadeAnimation,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildSectionTitle('请告诉我该如何称呼你', Icons.person_outline),
                      SizedBox(height: 16),
                      _buildNicknameInput(),
                      
                      SizedBox(height: 32),
                      
                      _buildSectionTitle('选择你的身份标签', Icons.local_offer_outlined),
                      SizedBox(height: 16),
                      _buildCustomTagInput(),
                      
                      SizedBox(height: 20),
                      _buildTagList(),
                      
                      SizedBox(height: 40),
                      _buildStartButton(),
                    ],
                  ),
                ),
              ),
              
                            SizedBox(height: 40),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSectionTitle(String title, IconData icon) {
    return Row(
      children: [
        Container(
          padding: EdgeInsets.all(8),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFF667eea), Color(0xFF764ba2)],
            ),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Icon(
            icon,
            color: Colors.white,
            size: 20,
          ),
        ),
        SizedBox(width: 12),
        Expanded(
          child: Text(
            title,
                              style: TextStyle(
                                fontSize: 18,
              fontWeight: FontWeight.w700,
              color: Colors.grey[800],
            ),
                              ),
                            ),
      ],
    );
  }

  Widget _buildNicknameInput() {
    return Container(
                              decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFFF8F9FA), Color(0xFFE9ECEF)],
        ),
        borderRadius: BorderRadius.circular(20),
                                boxShadow: [
                                  BoxShadow(
            color: Colors.black.withOpacity(0.05),
                                    blurRadius: 10,
                                    offset: Offset(0, 4),
                                  ),
                                ],
                              ),
                              child: TextField(
                                controller: _nicknameController,
        style: TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w500,
        ),
                                decoration: InputDecoration(
          hintText: '💭 输入你的昵称...',
          hintStyle: TextStyle(
            color: Colors.grey[500],
            fontWeight: FontWeight.w400,
          ),
                                  border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(20),
                                    borderSide: BorderSide.none,
                                  ),
          contentPadding: EdgeInsets.symmetric(horizontal: 24, vertical: 20),
          filled: true,
          fillColor: Colors.transparent,
                              ),
                            ),
    );
  }

  Widget _buildCustomTagInput() {
    return Container(
                              decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFFF8F9FA), Color(0xFFE9ECEF)],
        ),
        borderRadius: BorderRadius.circular(20),
                                boxShadow: [
                                  BoxShadow(
            color: Colors.black.withOpacity(0.05),
                                    blurRadius: 10,
                                    offset: Offset(0, 4),
                                  ),
                                ],
                              ),
                              child: Row(
                                children: [
                                  Expanded(
                                    child: TextField(
                                      controller: _customTagController,
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
                                      decoration: InputDecoration(
                hintText: '🏷️ 添加自定义标签...',
                hintStyle: TextStyle(
                  color: Colors.grey[500],
                  fontWeight: FontWeight.w400,
                ),
                                        border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                                          borderSide: BorderSide.none,
                                        ),
                contentPadding: EdgeInsets.symmetric(horizontal: 24, vertical: 20),
                filled: true,
                fillColor: Colors.transparent,
                                      ),
                                      onSubmitted: (_) => _addCustomTag(),
                                    ),
                                  ),
          Container(
            margin: EdgeInsets.only(right: 8),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [Color(0xFF667eea), Color(0xFF764ba2)],
              ),
              borderRadius: BorderRadius.circular(16),
              boxShadow: [
                BoxShadow(
                  color: Color(0xFF667eea).withOpacity(0.3),
                  blurRadius: 8,
                  offset: Offset(0, 4),
                ),
              ],
            ),
                                    child: ElevatedButton(
                                      onPressed: _addCustomTag,
                                      style: ElevatedButton.styleFrom(
                backgroundColor: Colors.transparent,
                                        foregroundColor: Colors.white,
                elevation: 0,
                                        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 16),
                                        shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
              ),
              child: Text(
                '添加',
                style: TextStyle(
                  fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
    );
  }

  Widget _buildTagList() {
    return Container(
                              decoration: BoxDecoration(
                                color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: Colors.grey[200]!),
                                boxShadow: [
                                  BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 8,
            offset: Offset(0, 2),
                                  ),
                                ],
                              ),
      child: Column(
        children: _availableTags.asMap().entries.map((entry) {
          final index = entry.key;
          final tag = entry.value;
                                  final isSelected = _selectedTags.contains(tag);
          final isLast = index == _availableTags.length - 1;
          
                                  return Container(
                                    decoration: BoxDecoration(
              border: !isLast ? Border(
                bottom: BorderSide(color: Colors.grey[100]!, width: 1),
              ) : null,
                                    ),
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: () {
                                        setState(() {
                    if (isSelected) {
                      _selectedTags.remove(tag);
                    } else {
                                            _selectedTags.add(tag);
                                          }
                                        });
                                      },
                borderRadius: BorderRadius.circular(20),
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 20, vertical: 16),
                  child: Row(
                    children: [
                      AnimatedContainer(
                        duration: Duration(milliseconds: 200),
                        width: 24,
                        height: 24,
                        decoration: BoxDecoration(
                          gradient: isSelected ? LinearGradient(
                            colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                          ) : null,
                          color: isSelected ? null : Colors.grey[300],
                          borderRadius: BorderRadius.circular(6),
                                  ),
                        child: isSelected ? Icon(
                          Icons.check,
                          color: Colors.white,
                          size: 16,
                        ) : null,
                      ),
                      SizedBox(width: 16),
                      Expanded(
                                child: Text(
                          tag,
                                  style: TextStyle(
                            color: isSelected ? Colors.grey[800] : Colors.grey[600],
                            fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
                            fontSize: 16,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildStartButton() {
    return Container(
      width: double.infinity,
      height: 60,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFF667eea), Color(0xFF764ba2)],
        ),
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Color(0xFF667eea).withOpacity(0.4),
            blurRadius: 20,
            offset: Offset(0, 10),
          ),
        ],
      ),
      child: ElevatedButton(
        onPressed: _saveUserInfoAndinitDifydataset,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.transparent,
          foregroundColor: Colors.white,
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.rocket_launch, size: 24),
            SizedBox(width: 12),
            Text(
              '开始使用知拾',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w700,
                letterSpacing: 0.5,
              ),
            ),
          ],
              ),
            ),
    );
  }
} 